<template>
  <div class="page-container">
    <el-card class="box-card">
      <!-- 步骤导航 -->
      <el-steps
        style="max-width: 600px; margin-bottom: 24px"
        :active="activeStep"
        finish-status="success"
      >
        <el-step title="忘记密码" />
        <el-step title="输入验证码" />
        <el-step title="创建新密码" />
      </el-steps>

      <!-- 动态表单内容，根据步骤切换 -->
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <!-- 步骤 1：忘记密码（仅输入手机号） -->
        <template v-if="activeStep === 0">
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="form.mobile"
              placeholder="请输入注册手机号"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleNextStep">
              下一步
            </el-button>
            <el-button
              type="info"
              @click="handleCancel"
              style="margin-left: 8px"
            >
              取消
            </el-button>
          </el-form-item>
        </template>

        <!-- 步骤 2：输入验证码（在这里发送验证码） -->
        <template v-else-if="activeStep === 1">
          <el-form-item label="手机号" disabled>
            <el-input v-model="form.mobile" disabled placeholder="注册手机号" />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input
              v-model="form.code"
              placeholder="请输入收到的验证码"
              clearable
              style="width: 240px; margin-right: 8px"
            />
            <el-button
              type="primary"
              @click="handleSendCode"
              :disabled="countdown > 0 || isSending"
            >
              {{ countdown > 0 ? `${countdown} 秒后重发` : "发送验证码" }}
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="handleNextStep"
              :loading="isVerifying"
            >
              验证并下一步
            </el-button>
            <el-button
              type="info"
              @click="handlePrevStep"
              style="margin-left: 8px"
            >
              返回
            </el-button>
          </el-form-item>
        </template>

        <!-- 步骤 3：创建新密码 -->
        <template v-else-if="activeStep === 2">
          <el-form-item label="新密码" prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入新密码"
              clearable
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="handleSubmit"
              :loading="isSubmitting"
            >
              确认重置密码
            </el-button>
            <el-button
              type="info"
              @click="handlePrevStep"
              style="margin-left: 8px"
            >
              返回
            </el-button>
          </el-form-item>
        </template>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";
import { SendMobile, userForgot } from "../api/api";
import { useRouter } from "vue-router";

const router = useRouter();

// 步骤控制
const activeStep = ref(0); // 0: 忘记密码  1: 输入验证码  2: 创建新密码

// 表单数据
const form = reactive({
  mobile: "",
  code: "",
  password: "",
  confirmPassword: "",
});

// 加载状态
const isSending = ref(false); // 发送验证码加载
const isVerifying = ref(false); // 验证验证码加载
const isSubmitting = ref(false); // 提交新密码加载

// 倒计时（重发验证码）
const countdown = ref(0);
let timer: number | undefined; // 用于清除定时器

/**
 * 下一步处理
 */
const handleNextStep = () => {
  if (activeStep.value === 0) {
    // 步骤 1 到 步骤 2 的验证
    if (!form.mobile) {
      ElMessage.error("请输入手机号！");
      return;
    }
    // 简单的手机号格式验证
    const phoneReg =
      /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    if (!phoneReg.test(form.mobile)) {
      ElMessage.error("请输入正确的手机号！");
      return;
    }
    activeStep.value = 1; // 进入步骤 2（验证码步骤）
  } else if (activeStep.value === 1) {
    // 步骤 2 到 步骤 3 的验证
    if (!form.code) {
      ElMessage.error("请输入验证码！");
      return;
    }

    // 模拟验证码校验
    isVerifying.value = true;
    setTimeout(() => {
      isVerifying.value = false;
      activeStep.value = 2; // 进入步骤 3（重置密码）
    }, 1500);
  }
};

/**
 * 发送验证码（步骤 2 专用）
 */
const handleSendCode = async () => {
  // 1. 校验手机号（提前拦截无效输入）
  if (!form.mobile) {
    ElMessage.error("请输入手机号！");
    return;
  }

  // 2. 开始加载状态
  isSending.value = true;

  try {
    // 3. 调用真实接口（替换为你的实际接口）
    const res = await SendMobile(form.mobile);

    // 4. 接口成功回调
    ElMessage.success("验证码已发送，请注意查收！" + res.data.data);

    // 5. 启动倒计时
    startCountdown();
  } catch (error) {
    // 6. 接口失败处理
    ElMessage.error("发送失败，请稍后重试！");
  } finally {
    // 7. 无论成功/失败，关闭加载状态
    setTimeout(() => {
      isSending.value = false;
    }, 500); // 延迟关闭，避免按钮闪烁
  }
};

// 启动倒计时（单独抽离）
const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
    }
  }, 1000);
};

/**
 * 返回上一步
 */
const handlePrevStep = () => {
  if (activeStep.value > 0) {
    activeStep.value--;
    // 回到步骤 1 时，清除倒计时
    if (activeStep.value === 0) {
      clearCountdown();
    }
  }
};

/**
 * 取消操作
 */
const handleCancel = () => {
  // 实际项目中可以跳回登录页
  ElMessage.info("已取消找回密码");
  router.push("/");
};

/**
 * 提交新密码（完成重置）
 */
const handleSubmit = () => {
  // 密码验证
  if (!form.password) {
    ElMessage.error("请输入新密码！");
    return;
  }

  // 密码长度验证
  if (form.password.length < 6 || form.password.length > 20) {
    ElMessage.error("密码长度必须在6-20个字符之间！");
    return;
  }

  // 确认密码验证
  if (form.password !== form.confirmPassword) {
    ElMessage.error("两次输入的密码不一致，请检查！");
    return;
  }

  // 模拟提交请求
  isSubmitting.value = true;
  setTimeout(() => {
    userForgot(form).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("密码重置成功！");
        router.push("/");
        isSubmitting.value = false;
      }
    });
  }, 1500);
};

/**
 * 启动倒计时（60秒）
 */
// const startCountdown = () => {
//   countdown.value = 60;
//   timer = window.setInterval(() => {
//     if (countdown.value > 0) {
//       countdown.value--;
//     } else {
//       clearCountdown();
//     }
//   }, 1000);
// };

/**
 * 清除倒计时
 */
const clearCountdown = () => {
  countdown.value = 0;
  if (timer) {
    clearInterval(timer);
  }
};
</script>

<style scoped>
.page-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.box-card {
  width: 100%;
  max-width: 600px;
  padding: 24px;
  margin: 24px auto;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-steps {
  margin-bottom: 24px;
}

.el-form-item {
  margin-bottom: 16px;
}
</style>
